<?php
/**
 * 人人站CMS
 * ============================================================================
 * 版权所有 2015-2030 山东康程信息科技有限公司，并保留所有权利。
 * 网站地址: http://www.rrzcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */

namespace app\admin\controller;


class Site extends Base
{
    /**
     * 导航菜单
     */
    function menus() {

        $this->pagedata['tabs'] = [
            ['name' => '导航菜单'],
        ];
        $this->pagedata['actions'] = [
            ['label' => '添加一级菜单', 'target' => 'dialog', 'href' => U('Site/addMenus'), 'options' => '{title:"添加菜单",area:["450px"]}'],
        ];

        $this->pagedata['columns'] = [
            ['field' => 'id', 'title' => 'ID', 'width' => '100',],
            ['field' => 'title','class' => 'js-lanmu', 'title' => '＋ 菜单名称', 'width' => '550', 'align' => 'left', 'callback' => function ($item) {
                $w = 20 * $item['depth'];
                return '<i class="layui-icon layui-icon-subtraction mr5"></i><span class="w40x" style="width:' . $w . 'px"></span><span>' . $item['title'] . '</span>';
            }],
            ['field' => 'sort', 'title' => '排序', 'width' => '70', 'callback' => function ($item) {
                return '<input  href="' . U('Site/sortMenus') . '" class="layui-input layui-input-sm js-sort" data-val="' . $item['sort'] . '" value="' . $item['sort'] . '"  maxlength="3" type="text" />';
            }],
            ['field' => 'cz', 'title' => '操作', 'width' => '300', 'align' => 'left', 'callback' => function ($item) {
                $html = '';
                $html .= '<a href="' . U('Site/addMenus', ['pid' => $item['id'],]) . '" options="{title:\'添加菜单\',area:[\'450px\']}" target="dialog" class="layui-btn layui-btn-primary layui-btn-xs"">添加下级菜单</a>';
                $html .= '<a href="' . U('Site/addMenus', ['id' => $item['id'], 'pid' => $item['parent_id'],]) . '" options="{title:\'编辑菜单\',area:[\'450px\']}" target="dialog" class="layui-btn layui-btn-xs">编辑</a>';
                $html .= '<a href="' . U('Site/delMenus', ['id' => $item['id'],]) . '" msg="确定要删除吗？<p class=\'f12 cl-f44\'>下级菜单也将会被删除！</p>" target="confirm" class="layui-btn layui-btn-danger layui-btn-xs">删除</a>';
                return $html;
            }],
        ];
        $data = M('site_menus')->field('id,title,depth,sort,parent_id,id_path')
            ->order('path asc,id asc')
            ->select()->toArray();

        $this->pagedata['data'] = tierMenusList($data);

        $this->pagedata['trAttr'] = [
            'pid' => 'parent_id',
        ];//表格行属性
        $this->pagedata['pk_field'] = 'id';
        $this->pagedata['fixedColumn'] = true;
        $this->pagedata['isPage'] = false;
        $this->pagedata['grid_class'] = 'js-view-menus';

        return $this->grid_fetch();
    }

    /**
     * 菜单排序
     * @throws \Exception
     */
    function sortMenus() {
        $id = I('post.id');
        $sort = I('post.sort', 0);
        if (!is_numeric($id) || !is_numeric($sort)) $this->error();

        $row = M('site_menus')->where('id', $id)->field('path,id_path')->find();
        $path = $row['path'];
        $path = substr($path, 0, -4) . (1000 + ($sort > 1000 ? 999 : $sort));

        $rs = M('site_menus')->where('id', $id)->save(['sort' => $sort, 'path' => $path,]);
        $rs or $this->error();

        $len = strlen($path) + 1;
        M('site_menus')->where('id_path', 'like', $row['id_path'] . ',%')
            ->exp('path', "concat('{$path}',substring(path,{$len}))")->update();

        $this->success('', true);
    }

    /**
     * 删除菜单
     */
    function delMenus() {
        $id = I('get.id');
        is_numeric($id) or $this->error('参数不合法！');

        $path = M('site_menus')->where('id', $id)->value('id_path');
        $where = ' id=' . $id;
        $path and $where .= " or(id_path like '{$path},%') ";

        $rs = M('site_menus')->whereRaw($where)->delete();
        $rs or $this->error('删除失败！');
        $this->success('删除成功！', true);
    }

    /**
     * 添加菜单
     */
    function addMenus() {
        if (!$this->request->isPost()) {
            $pid = I('get.pid');
            if (is_numeric($pid) && $pid > 0) {
                $title = M('site_menus')->where('id', $pid)->value('title');
                if ($title) {
                    $this->assign('ptitle', $title);
                    $this->assign('pid', $pid);
                }
            }
            $id = I('get.id');
            $id and $row = M('site_menus')->where('id', $id)->find();

            $this->assign('row', $row ?? []);
            return $this->fetch();
        }

        $id = I('get.id');
        $data = I('post.');
        $data['title'] = trim($data['title']) or $this->error('请填写菜单名称！');
        if ($data['dir_name'] && preg_match('/[^a-zA-Z0-9_]/', $data['dir_name'])) {
            $this->error('目录名称错误，仅支持字母、数字、下划线！');
        }
        $data['dir_name'] = preg_replace('/\s+/', '', $data['dir_name']);//替换空格
        if ($data['dir_name'] && $this->dirnameIsHas($data['dir_name'], $id)) {
            $this->error('目录名称已存在，请更改！');
        }
        $data['dir_name'] = $this->get_dirname($data['title'], $data['dir_name'], $id);
        if ($id && is_numeric($id)) {
            $rs = M('site_menus')->where('id', $id)->save($data);
            $rs === false and $this->error('保存失败！');
            $this->success('保存成功！', true);
        }
        $pid = isset($data['parent_id']) && is_numeric($data['parent_id']) ? $data['parent_id'] : 0;

        $pInfo = M('site_menus')->where('id', $pid)->field('depth,path,id_path')->find();
        $sort = M('site_menus')->where('parent_id', $pid)->max('sort');
        $sort = $sort ? $sort + 1 : 1;

        $data['depth'] = ($pInfo['depth'] ?? 0) + 1;
        $data['path'] = ($pInfo['path'] ?? '') . (1000 + ($sort > 1000 ? 999 : $sort));
        $data['sort'] = $sort;

        $rId = M('site_menus')->insert($data, true);
        $rId or $this->error('保存失败！');

        M('site_menus')->where('id', $rId)->save([
            'id_path' => (isset($pInfo['id_path']) && $pInfo['id_path'] ? $pInfo['id_path'] . ',' : '') . $rId
        ]);

        $this->success('保存成功！', true);
    }

    /*
     * 判断是否存在目录名称
     */
    private function dirnameIsHas($dirname, $id = 0) {
        $where = [
            ['dir_name', '=', $dirname],
            ['id', '<>', $id],
        ];
        $has = M('site_menus')->where($where)->count();
        return $has > 0;
    }

    /*
     * 获取目录名称
     */
    private function get_dirname($title = '', $dirname = '', $id = 0) {
        if (!trim($dirname) || empty($dirname)) {
            $pinyin = new \app\admin\lib\Piyin();
            $s1 = iconv('UTF-8', 'gbk//IGNORE', $title);
            $s2 = iconv('gbk', 'UTF-8//IGNORE', $s1);
            if ($s2 == $title) {
                $title = $s1;
            }
            $dirname = $pinyin->getFullSpell($title);
            $dirname = preg_replace('/\s+/', '_', $dirname);
            $dirname = strtolower($dirname);
        }
        $dirname = preg_replace('/[^a-zA-Z0-9_]/', '', $dirname);
        $dirname = preg_replace('/[_]{1,}/', '_', $dirname);

        if (strval(intval($dirname)) == strval($dirname)) {
            $dirname .= get_rand_str(3, 0, 2);
        }
        if ($this->dirnameIsHas($dirname, $id)) {
            $nowDirname = $dirname . get_rand_str(3, 0, 2);
            return $this->get_dirname($title, $nowDirname);
        }
        return $dirname;
    }


    /**
     * 站点配置
     */
    function setting() {
        $this->assign('website', sysConfig('website'));
        $this->assign('admin', sysConfig('admin'));
        $this->assign('webinfo', sysConfig('webinfo'));
        $this->assign('webfilter', sysConfig('webfilter'));
        return $this->fetch();
    }

    /**
     * 保存配置
     */
    function saveConfig() {
        $data = I('post.');
        $url = '';
        foreach ($data as $key => $item) {
            if ($key == 'admin') {
                $old = sysConfig('admin.app_map') ?: 'admin';
                if ($item['app_map'] != $old) {
                    $map = trim($item['app_map']);
                    $this->setAdminMap($map);
                    $url = U('Index/index');
                    $url = str_replace('/' . $old, '/' . $map, $url);
                    $item['app_map'] = $map;
                }
            }
            sysConfig($key, $item);
        }
        $data = '';
        $url = $data = ['jump' => $url];
        return $this->success('保存成功！', $data);
    }

    private function setAdminMap($map) {
        $file = $this->app->getRootPath() . '.env';
        $strConfig = file_get_contents($file);
        $strConfig = preg_replace('/ADMIN_MAP(\s+)?=(\s+)?(\w+)/', "ADMIN_MAP = {$map}", $strConfig);
        file_put_contents($file, $strConfig);
        return true;
    }

}